package light.head.controller.el;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.el.ClassCourseTopicRelationDAO;
import light.head.dao.el.ClassesCourseRelationDAO;
import light.head.dao.el.ClassesDAO;
import light.head.dao.el.CourseDAO;
import light.head.dao.el.ExamRecordDAO;
import light.head.dao.el.PaperTemplateDAO;
import light.head.dao.el.PaperTemplateItemDAO;
import light.head.dao.el.TopicDAO;
import light.head.dao.el.UserClassesRelationDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.Organ;
import light.head.model.UserInfo;
import light.head.model.el.ClassCourseTopicRelation;
import light.head.model.el.Classes;
import light.head.model.el.ClassesCourseRelation;
import light.head.model.el.CourseLecturer;
import light.head.model.el.ExamRecord;
import light.head.model.el.PaperTemplate;
import light.head.model.el.UserClassesRelation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 班级管理 
 */
@Controller
@RequestMapping(Url.C_CLASSES)
public class ClassesController extends SupporterController{
	
	private ClassesDAO cDAO;
	private CourseDAO courseDAO;
	private UserInfoDAO uDAO;
	private PaperTemplateDAO ttDAO;
	private PaperTemplateItemDAO tiDAO;
	private TopicDAO topicDAO;
	private ClassesCourseRelationDAO ccrDAO;
	private UserClassesRelationDAO ucrDAO;
	private ClassCourseTopicRelationDAO cctrDAO;
	private ExamRecordDAO erDAO;
	private OrganDAO organDAO;
	

	@RequestMapping(Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response){
		return new ModelAndView(Url.CLASSES_INIT);
	}
	
	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response){
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME,Parm.DELETED);
		if(cDAO.findByMap(organDAO.getSonCodeList(oc), map, pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.CLASSES_LIST);
	}
	
	@RequestMapping(Url.EDIT)
	public ModelAndView edit(Integer code, HttpServletRequest request, HttpServletResponse response){
		if(code != null){
			Classes c = cDAO.get(code);
			if(c != null){
				c.setCcrList(ccrDAO.findByCcrCode(c.getCode()));
				c.setUcrList(ucrDAO.findByClcCodeAndStatus3(c.getCode()));
				c.setCctrList(cctrDAO.findByClcCode(c.getCode()));
			}
			request.setAttribute(Parm.INFO, c);
		}
		return new ModelAndView(Url.CLASSES_EDIT);
	}
	
	
	@RequestMapping("passRate")
	public ModelAndView passRate(Integer code, HttpServletRequest request, HttpServletResponse response){
		if(code != null){
			Classes c = cDAO.get(code);
			if(c != null){
				List<ClassesCourseRelation> ccrList = ccrDAO.findByCcrCode(c.getCode());
				List<UserClassesRelation> ucrList = ucrDAO.findByClcCode(c.getCode());
				int ucr = ucrList.size();
				int passman = 0;
				for (ClassesCourseRelation ccr : ccrList) {
					List<ExamRecord> leran2List = erDAO.findByPass(code, ccr.getCc());			//考试通过的
					passman = leran2List.size();
					if(ucrList.size() > 0 && leran2List.size() == 0){
						ccr.setPassRate(0.0);
						ccrDAO.upd(ccr);
					}else if(ucrList.size() == 0 && leran2List.size() == 0){
						ccr.setPassRate(0.0);
						ccrDAO.upd(ccr);
					}else if(ucrList.size() > 0 && leran2List.size() > 0){
						double a = leran2List.size() * 1.0;
						double b = ucrList.size() * 1.0;
						double pass= a/b;
						/*DecimalFormat df1 = new DecimalFormat("##.00%");
						String baifenbi = df1.format(pass);*/
						ccr.setPassRate(pass * 100);
						ccrDAO.upd(ccr);
					}
					
				}
				c.setCcrList(ccrList);
				request.setAttribute("ucr", ucr);
				request.setAttribute("passman", passman);
				/*c.setUcrList(ucrDAO.findByClcCodeAndStatus3(c.getCode()));*/
				/*c.setCctrList(cctrDAO.findByClcCode(c.getCode()));*/
			}
			request.setAttribute(Parm.INFO, c);
		}
		return new ModelAndView(Url.CLASSES_PASSRATE);
	}
	
	/**
	 * 报名管理
	 */
	@RequestMapping(Url.CLASSESSIGNINIT)
	public ModelAndView classSignInit(Integer code, HttpServletRequest request, HttpServletResponse response){
		request.setAttribute(Parm.CODE, code);
		return new ModelAndView(Url.CLASSESSIGN_INIT);
	}
	
	@RequestMapping(Url.CLASSESSIGNLIST)
	public ModelAndView classSignList( HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME,Parm.CODE,Parm.STATUS,Parm.DELETED);
		if(ucrDAO.findByMap(cu_organCode(request), map , pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.CLASSESSIGN_LIST);
	}
	
	@RequestMapping(Url.CLASSESSIGNALLSIGN)
	public void allSign(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		RESULT result = RESULT.ERROR;
		if(code != null){
			result = ucrDAO.updateAllSign(Integer.parseInt(code));
		}
		if(result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	@RequestMapping(Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		RESULT result = RESULT.ERROR;
		if(code != null){
			Classes c = cDAO.get(Integer.parseInt(code));
			if(c != null){
				c.setDeleted(true);
				result = cDAO.upd(c);
			}
		}
		if(result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	@RequestMapping(Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		RESULT result = RESULT.ERROR;
		if(code != null){
			Classes c = cDAO.get(Integer.parseInt(code));
			if(c != null){
				c.setDeleted(false);
				result = cDAO.upd(c);
			}
		}
		if(result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	@RequestMapping(Url.PASS)
	public void shieldSign(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		String uc = request.getParameter(Parm.UC);
		RESULT result = RESULT.ERROR;
		if(code != null && uc != null){
			UserClassesRelation ucr = ucrDAO.getUcrByClcAndUc(Integer.parseInt(code),Integer.parseInt(uc));
			if(ucr != null){
				ucr.setStatus(Byte.parseByte(Sys.S_THREE));
				result = ucrDAO.upd(ucr);
			}
		}
		if(result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}

	@RequestMapping(Url.UNPASS)
	public void unShieldSign(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		String uc = request.getParameter(Parm.UC);
		RESULT result = RESULT.ERROR;
		if(code != null && uc != null){
			UserClassesRelation ucr = ucrDAO.getUcrByClcAndUc(Integer.parseInt(code),Integer.parseInt(uc));
			if(ucr != null){
				ucr.setStatus(Byte.parseByte(Sys.S_TWO));
				result = ucrDAO.upd(ucr);
			}
		}
		if(result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	/**
	 * 保存
	 */
	@RequestMapping(Url.SAVE)
	@Transactional(rollbackFor = Exception.class)
	public void save(Classes c, HttpServletRequest request, HttpServletResponse response){
		RESULT result = RESULT.ERROR;
		if(c == null){
			print(response, Msg.ERROR);
		}
		Integer oc = cu_organCode(request);
		Integer occ = organDAO.getRoot(oc).getCode();
		Date time = new Date();
		if(c.getCode() == null){
			//新班级保存
			c.setDeleted(false);
			c.setCu(cu_code(request));
			c.setCt(time);
			c.setOc(oc);
			result = cDAO.add(c);
			if(result == RESULT.SUCCESS){
				for(ClassesCourseRelation ccr : c.getCcrList()){
					if(ccr != null && ccr.getCc() != null){
						ccr.setClc(c.getCode());
						if(ccrDAO.add(ccr) != RESULT.SUCCESS){
							throw new RuntimeException("操作失败!");
						}
					}
				}
				if(c.getHow() == 3){
					for(UserClassesRelation ucr : c.getUcrList()){
						if(ucr != null && ucr.getUc() != null){
							ucr.setOc(occ);
							ucr.setClc(c.getCode());
							ucr.setSignTime(time);
							ucr.setStatus(Byte.parseByte(Sys.S_THREE));
							if(ucrDAO.add(ucr) != RESULT.SUCCESS){
								throw new RuntimeException("操作失败!");
							}
						}
					}
				}
				if(c.getCctrList() != null){
					for(ClassCourseTopicRelation cctr : c.getCctrList()){
						if(cctr.getCc() != null && cctr.getTc() != null){
							cctr.setClc(c.getCode());
							if(cctrDAO.add(cctr) != RESULT.SUCCESS){
								throw new RuntimeException("操作失败!");
							}
						}
					}
				}
				result = RESULT.SUCCESS;
			}
		}else{
			//更新班级
			result = cDAO.update(c);
			if(result == RESULT.SUCCESS){
				//课程保存
				List<ClassesCourseRelation> oldCcrList = ccrDAO.findByCcrCode(c.getCode());
				List<ClassesCourseRelation> updCcrList = new ArrayList<ClassesCourseRelation>();
				List<ClassesCourseRelation> addCcrList = new ArrayList<ClassesCourseRelation>();
				List<ClassesCourseRelation> ccrList = c.getCcrList();
				for(ClassesCourseRelation ccr : ccrList){
					if(ccr != null && ccr.getCc() != null){
						for(ClassesCourseRelation oldCcr : oldCcrList){
							if(ccr.getCc().intValue() == oldCcr.getCc().intValue()){
								updCcrList.add(oldCcr);
								addCcrList.add(ccr);
							}
						}
					}
				}
				
				//删除
				for(ClassesCourseRelation ycc : updCcrList){
					oldCcrList.remove(ycc);
				}
				List<ClassCourseTopicRelation> temp = null;
				for(ClassesCourseRelation delCcr : oldCcrList){
					temp = cctrDAO.findByClcAndCc(c.getCode(), delCcr.getCc());
					if(temp != null && temp.size() > 0){
						cctrDAO.delAll(temp);
					}
					ccrDAO.del(delCcr);
				}
				
				//增加
				for(ClassesCourseRelation yicc : addCcrList){
					ccrList.remove(yicc);
				}
				
				for(ClassesCourseRelation addCcr : ccrList){
					if(addCcr != null && addCcr.getCc() != null){
						addCcr.setClc(c.getCode());
						ccrDAO.add(addCcr);
					}
				}
				
				//修改
				for(ClassesCourseRelation updCcr : addCcrList){
					ccrDAO.update(updCcr);
				}
				
				
				//更新学生信息
				List<UserClassesRelation> oldUcrList = ucrDAO.findByClcCode(c.getCode());
				List<UserClassesRelation> updUcrList = new ArrayList<UserClassesRelation>();
				List<UserClassesRelation> addUcrList = new ArrayList<UserClassesRelation>();
				List<UserClassesRelation> ucrList = c.getUcrList();
				if( ucrList != null && ucrList.size() > 0){
					for(UserClassesRelation ucr : ucrList){
						if(ucr != null && ucr.getUc() != null){
							for(UserClassesRelation oldUcr : oldUcrList){
								if(ucr.getUc().intValue() == oldUcr.getUc().intValue()){
									updUcrList.add(oldUcr);
									addUcrList.add(ucr);
								}
							}
						}
					}
					//增加
					for(UserClassesRelation acmr : addUcrList){
						ucrList.remove(acmr);
					}
					for(UserClassesRelation add : ucrList){
						if(add != null && add.getUc() != null){
							add.setOc(occ);
							add.setClc(c.getCode());
							add.setSignTime(time);
							add.setStatus(Byte.parseByte(Sys.S_THREE));
							ucrDAO.add(add);
						}
					}
					//删除
					for(UserClassesRelation remUcr : updUcrList){
						oldUcrList.remove(remUcr);
					}
					ucrDAO.delAll(oldUcrList);
				} else {
					if(oldUcrList != null && oldUcrList.size() > 0){
						ucrDAO.delAll(oldUcrList);
					}
				}
				//更新 题目信息
				List<ClassCourseTopicRelation> oldCctrList = cctrDAO.findByClcCode(c.getCode());
				List<ClassCourseTopicRelation> updCctrList = new ArrayList<ClassCourseTopicRelation>();
				List<ClassCourseTopicRelation> addCctrList = new ArrayList<ClassCourseTopicRelation>();
				List<ClassCourseTopicRelation> cctrList = c.getCctrList();
				if(cctrList != null && cctrList.size() > 0){
					for(ClassCourseTopicRelation cctr : cctrList){
						if(cctr != null && cctr.getCc() != null && cctr.getTc() != null){
							for(ClassCourseTopicRelation oldCctr : oldCctrList){
								if(cctr.getCc().intValue() == oldCctr.getCc().intValue() && cctr.getTc().intValue() == oldCctr.getTc().intValue()){
									updCctrList.add(oldCctr);
									addCctrList.add(cctr);
								}
							}
						}
					}
					//删除
					for(ClassCourseTopicRelation ycc : updCctrList){
						oldCctrList.remove(ycc);
					}
					for(ClassCourseTopicRelation delCctr : oldCctrList){
						cctrDAO.del(delCctr);
					}
					//增加
					for(ClassCourseTopicRelation yicc : addCctrList){
						cctrList.remove(yicc);
					}
					
					for(ClassCourseTopicRelation addCctr : cctrList){
						if(addCctr != null && addCctr.getCc() != null && addCctr.getTc() != null){
							addCctr.setClc(c.getCode());
							cctrDAO.add(addCctr);
						}
					}
					//修改
					for(ClassCourseTopicRelation updCctr : addCctrList){
						updCctr.setClc(c.getCode());
						cctrDAO.update(updCctr);
					}
				}else{
					if(oldCctrList != null && oldCctrList.size() > 0){
						cctrDAO.delAll(oldCctrList);
					}
				}
				result = RESULT.SUCCESS;
			}
		}
		
		if(result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		} else {
			print(response,Msg.ERROR);
		}
	}

	/**
	 * 辅助查询学生信息
	 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidInit1(HttpServletRequest request, HttpServletResponse response){
		String codes = request.getParameter(Parm.CODES);
		if(codes != null){
			request.setAttribute("tsCodes", codes);
		}
		return new ModelAndView(Url.USERCLASS_AIDINIT);
	}
	
	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidList1(HttpServletRequest request, HttpServletResponse response){
		Integer oc = cu_organCode(request);
		Organ o = organDAO.getRoot(oc);
		List<Object> ocs = new ArrayList<Object>();
		if(o != null){
			organDAO.findSubCode(o,ocs);
		}else{
			organDAO.findSubCode(organDAO.get(oc),ocs);
		}
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.REAL_NAME, Parm.DELETED, Parm.CODES);
		if(uDAO.aidFindByMap(ocs, map, pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		String codes = map.get(Parm.CODES);
		if(isNotNull(codes)){
			List<UserInfo> clist = uDAO.findUserByCodes(codes);
			request.setAttribute(Parm.LIST,clist);
		}
		return new ModelAndView(Url.USERCLASS_AIDLIST);
	}
	
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response){
		String cc = request.getParameter(Parm.CC);
		request.setAttribute(Parm.CC, cc);
		String i = request.getParameter(Parm.K);
		request.setAttribute(Parm.K, i);
		return new ModelAndView(Url.TOPICCLASS_AIDINIT);
	}
	
	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidList(HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.CONTENT, Parm.TYPE, Parm.TDC,Parm.CC);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if(topicDAO.findByMap(oc, map, pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.TOPICCLASS_AIDLIST);
	}
	
	
	/**
	 * 辅助查询题目信息(有模板的情况)
	 */
	@RequestMapping(Url.AID_INIT_2)
	public ModelAndView aidInit2(HttpServletRequest request, HttpServletResponse response){
		String ttc = request.getParameter(Parm.TTC);
		String cc = request.getParameter(Parm.CC);
		if(isNotNull(ttc)){
			PaperTemplate tt = ttDAO.get(Integer.parseInt(ttc));
			if(tt != null){
				tt.setList(tiDAO.findByTtc(tt.getCode()));
			}
			request.setAttribute(Parm.LIST_1,tt);
		}
		request.setAttribute(Parm.CC, cc);
		return new ModelAndView(Url.TOPICCLASS_AIDINIT2);
	}
	
	@RequestMapping(Url.AID_LIST_2)
	public ModelAndView aidList2(HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.CONTENT, Parm.TYPE, Parm.TDC,Parm.CC);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if(topicDAO.findByMap(oc, map, pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.TOPICCLASS_AIDLIST2);
	}
	@RequestMapping(Url.QUERYTC)
	public void queryTc(Integer cc,HttpServletRequest request, HttpServletResponse response){
		List<CourseLecturer> clList = courseDAO.findTc(organDAO.getRoot(cu_organCode(request)).getCode(), cc);
		if(clList != null && clList.size() > 0){
			StringBuffer result = new StringBuffer();
			for(CourseLecturer t :clList) {
				result.append("<option value= \"" + t.getLc() +"\">");
				result.append(t.getLn());
				result.append("</option>");
			}
			print(response, result.toString());
		}
	}
	
	
	@Autowired
	public void setcDAO(ClassesDAO cDAO) {
		this.cDAO = cDAO;
	}
	@Autowired
	public void setuDAO(UserInfoDAO uDAO) {
		this.uDAO = uDAO;
	}
	@Autowired
	public void setTtDAO(PaperTemplateDAO ttDAO) {
		this.ttDAO = ttDAO;
	}
	@Autowired
	public void setTiDAO(PaperTemplateItemDAO tiDAO) {
		this.tiDAO = tiDAO;
	}

	@Autowired
	public void setTopicDAO(TopicDAO topicDAO) {
		this.topicDAO = topicDAO;
	}
	@Autowired
	public void setCcrDAO(ClassesCourseRelationDAO ccrDAO) {
		this.ccrDAO = ccrDAO;
	}
	@Autowired
	public void setCctrDAO(ClassCourseTopicRelationDAO cctrDAO) {
		this.cctrDAO = cctrDAO;
	}

	@Autowired
	public void setUcrDAO(UserClassesRelationDAO ucrDAO) {
		this.ucrDAO = ucrDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setCourseDAO(CourseDAO courseDAO) {
		this.courseDAO = courseDAO;
	}
	@Autowired
	public void setErDAO(ExamRecordDAO erDAO) {
		this.erDAO = erDAO;
	}
	
}
